package org.example;

import bean.ResponseUtils;
import bean.DB;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.*;
import java.nio.file.*;
import jakarta.servlet.annotation.MultipartConfig;
import java.sql.*;

@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 2,  // 2MB
        maxFileSize = 1024 * 1024 * 10,       // 10MB
        maxRequestSize = 1024 * 1024 * 50     // 50MB
)
@WebServlet("/productRegServlet") // URL映射
public class productRegServlet extends HttpServlet {

    // 处理POST请求
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单字段
        String productName = request.getParameter("productName");
        String price = request.getParameter("price");
        String description = request.getParameter("description");

        // 获取上传的图片
        Part imagePart = request.getPart("image");
        String imageFileName = Paths.get(imagePart.getSubmittedFileName()).getFileName().toString();  // 获取文件名

        // 设置图片保存的绝对路径
        String uploadPath = "C:\\Users\\DELL\\IdeaProjects\\productsManagerSys\\src\\main\\webapp\\image\\goodsImg\\" + imageFileName;

        // 创建文件夹（如果不存在）
        File uploadDir = new File("C:\\Users\\DELL\\IdeaProjects\\productsManagerSys\\src\\main\\webapp\\image\\goodsImg");
        if (!uploadDir.exists()) {
            if (uploadDir.mkdirs()) {
                System.out.println("成功创建文件夹: " + uploadDir.getAbsolutePath());
            } else {
                System.out.println("无法创建文件夹: " + uploadDir.getAbsolutePath());
            }
        }

        // 将文件保存到服务器
        try (InputStream inputStream = imagePart.getInputStream()) {
            Files.copy(inputStream, Paths.get(uploadPath), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("文件已成功保存到: " + uploadPath); // 输出文件保存路径
        } catch (IOException e) {
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "文件上传失败：" + e.getMessage(), "productPage.jsp");
            return;
        }

        String star = request.getParameter("star");

        // 使用DB类检查商品是否存在
        DB db = new DB();
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        boolean productExists = false;

        try {
            conn = db.createConn();

            // 查询是否已存在相同的商品
            String checkSql = "SELECT COUNT(*) FROM products WHERE product_name = ?";
            stmt = conn.prepareStatement(checkSql);
            stmt.setString(1, productName);
            rs = stmt.executeQuery();

            if (rs != null && rs.next()) {
                int count = rs.getInt(1);
                if (count > 0) {
                    productExists = true;  // 商品已经存在
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "数据库查询失败：" + e.getMessage(), "productPage.jsp");
            return;
        } finally {
            // 关闭资源
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (productExists) {
            ResponseUtils.sendResponse(response, "该商品已经存在，请选择其他商品名！", "productPage.jsp");
        } else {
            // 插入新商品
            String insertSql = "INSERT INTO products (product_name, price, description, image_path, star) VALUES (?, ?, ?, ?, ?)";
            try {
                conn = db.createConn();
                stmt = conn.prepareStatement(insertSql);
                stmt.setString(1, productName);
                stmt.setBigDecimal(2, new java.math.BigDecimal(price));
                stmt.setString(3, description);
                stmt.setString(4, "image/goodsImg/" + imageFileName);  // 存储图片相对路径
                stmt.setBigDecimal(5, new java.math.BigDecimal(star));

                int rowsAffected = stmt.executeUpdate();
                if (rowsAffected > 0) {
                    ResponseUtils.sendResponse(response, "商品注册成功！", "productPage.jsp"); // 成功时重定向
                } else {
                    ResponseUtils.sendResponse(response, "商品注册失败！", "productPage.jsp"); // 失败时重定向
                }
            } catch (SQLException e) {
                e.printStackTrace();
                ResponseUtils.sendResponse(response, "数据库操作失败：" + e.getMessage(), "productPage.jsp");
            } finally {
                // 关闭资源
                try {
                    if (stmt != null) stmt.close();
                    if (conn != null) conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
